package com.supermarket.manage.buiness.handler;

import com.supermarket.manage.common.dto.CodeStatus;
import com.supermarket.manage.common.dto.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;

/**
 * 参数校验异常拦截
 *
 * @author Faxon
 * @version 1.0
 * @date 2020-03-07 21:04
 **/
@ControllerAdvice
public class ValidationExceptionsHandler {
    private static final Logger log = LoggerFactory.getLogger(ValidationExceptionsHandler.class);

    /**
     * 功能描述：参数级的参数验证错误
     *
     * @param throwable
     * @return 返回处理结果
     * @throws Exception
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseBody
    public ResponseResult<Void> errorHandler(ConstraintViolationException throwable) throws Exception {
        StringBuilder sb = new StringBuilder();
        Set<ConstraintViolation<?>> violations = throwable.getConstraintViolations();
        violations.forEach(v -> {
            sb.append(v.getMessage()).append(",");
        });
        log.error("参数级的参数验证错误：{}", sb.deleteCharAt(sb.length() - 1));
        return new ResponseResult<>(CodeStatus.ILLEGAL_REQUEST, "参数非法:" + sb);
    }

    /**
     * 功能描述：参数级的参数验证错误
     *
     * @param throwable
     * @return 返回处理结果
     * @throws Exception
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseResult<Void> errorHandler(MethodArgumentNotValidException throwable) throws Exception {
        StringBuilder sb = new StringBuilder();
        List<FieldError> fieldErrors = throwable.getBindingResult().getFieldErrors();
        fieldErrors.forEach(e -> {
            sb.append(e.getDefaultMessage()).append(",");
        });
        log.error("实体类级的参数验证错误：{}", sb.deleteCharAt(sb.length() - 1));
        return new ResponseResult<>(CodeStatus.ILLEGAL_REQUEST, "参数非法:" + sb);
    }
}
